package shop.ynubeggar.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import shop.ynubeggar.constant.RedisCacheKey;
import shop.ynubeggar.request.AdminLoginRequest;
import shop.ynubeggar.request.AdminRegisterRequest;
import shop.ynubeggar.service.AdminService;
import shop.ynubeggar.utils.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "管理端认证")
@RestController
@RequestMapping("api/admin/v1")
@CrossOrigin(origins = "*")
public class AdminController {

    @Resource
    AdminService adminService;

    /**
     * 商家登录
     * @param adminLoginRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("login")
    @CrossOrigin(origins = "*")
    public String login(@ApiParam(value = "用户登录信息", required = true)
                        @RequestBody AdminLoginRequest adminLoginRequest,
                        HttpServletRequest request) {
        return adminService.adminLogin(adminLoginRequest, request);
    }

    /**
     * 商家注册：使用图形验证码验证
     * @param adminRegisterRequest
     * @param request
     */
    @ApiOperation(value = "注册",notes = "使用图形验证码验证")
    @PostMapping("register")
    public void register(@ApiParam(value = "用户注册信息", required = true)
                         @RequestBody AdminRegisterRequest adminRegisterRequest,
                         HttpServletRequest request) {
        String captchaKey = produceCaptchaKey(request);
        adminService.adminRegister(captchaKey, adminRegisterRequest);
    }



    /**
     * 获取验证码缓存的key
     *
     * @param request
     * @return
     */
    public static String produceCaptchaKey(HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        return String.format(RedisCacheKey.CHECK_CODE_KEY, CommonUtils.MD5(ip + userAgent));
    }

}
